<template>
  <!-- 选择渠道 -->
  <div class="left-container">
    <el-form
      ref="channelform"
      :model="channelform"
      :rules="rules"
      label-position="left"
      label-width="110px"
      size="mini"
      class="text-sm"
    >
      <!-- 起运地 -->
      <el-form-item prop="loadingPort">
        <div slot="label">起运地：</div>

        <el-tooltip
          class="item"
          content="点击填写可快速搜索"
          effect="light"
          placement="top-end"
        >
          <el-select
            v-model="channelform.loadingPort"
            filterable
            placeholder="请选择"
            @change="checkChannelSearchCriteria"
          >
            <el-option
              v-for="(item, value) in publicData.shippingAddressMap"
              :key="value"
              :label="item"
              :value="value"
            />
          </el-select>
        </el-tooltip>
      </el-form-item>
      <!-- 目的地 -->
      <el-form-item prop="countryId">
        <div slot="label">目的国家：</div>
        <el-tooltip
          class="item"
          content="点击填写可快速搜索"
          effect="light"
          placement="top-end"
        >
          <el-select
            v-model="channelform.countryId"
            filterable
            :disabled="orderType === 'quickOrder' ? true : false"
            placeholder="请选择"
            @change="retrieveAddress('add', 0)"
          >
            <el-option
              v-for="item in publicData.countryList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-tooltip>
      </el-form-item>
      <!-- 实重 体积 件数 -->
      <el-row :gutter="5">
        <el-col :sm="24" :md="24" :lg="8">
          <el-form-item prop="customerActualWeight">
            <div slot="label">实重(KG)：</div>

            <el-input
              v-model="channelform.customerActualWeight"
              @change="checkChannelSearchCriteria"
            />
          </el-form-item>
        </el-col>
        <el-col :sm="24" :md="24" :lg="8">
          <el-form-item prop="customerTotalPackages" class="text-right">
            <div slot="label">件数：</div>

            <el-input
              v-model.number="channelform.customerTotalPackages"
              :disabled="orderType === 'quickOrder' ? true : false"
            />
          </el-form-item>
        </el-col>
        <!-- 海运需要关联体积 -->
        <el-col :sm="24" :md="24" :lg="8">
          <el-form-item prop="customerVolume" class="text-right">
            <div slot="label">体积(CBM)：</div>

            <el-input
              v-model="channelform.customerVolume"
              @change="changeCustomerVolume"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- FBA -->
      <el-form-item
        v-if="orderType !== 'quickOrder'"
        prop="purposeWarehouseType"
      >
        <div slot="label">目的仓库类型：</div>
        <el-radio-group
          ref="aaa"
          v-model="channelform.purposeWarehouseType"
          @change="retrieveAddress('add', 1)"
        >
          <template v-for="(item, value) in publicData.stockTypeEnableMap">
            <template v-if="value != 200">
              <el-radio :key="value" :label="parseInt(value)">
                {{ item }}
              </el-radio>
            </template>
          </template>
        </el-radio-group>
        <!-- <el-tooltip
          class="icon-absolute item"
          content="您的最终派送地址是否FBA？"
          effect="light"
          placement="right"
        >
          <i class="el-icon-question icon-question text-yellow" />
        </el-tooltip> -->
      </el-form-item>
      <!-- 其他仓库类型 -->
      <div v-if="channelform.purposeWarehouseType === 700">
        <el-form-item prop="dispatcher">
          <div slot="label">公司名/个人：</div>
          <el-input v-model="channelform.dispatcher" clearable />
        </el-form-item>
        <el-form-item prop="dispatchLinkMan">
          <div slot="label">联系人：</div>
          <el-input v-model="channelform.dispatchLinkMan" clearable />
        </el-form-item>
        <el-form-item prop="dispatchPhone">
          <div slot="label">联系电话：</div>
          <el-input v-model="channelform.dispatchPhone" clearable />
        </el-form-item>
        <el-form-item prop="dispatchEmail">
          <div slot="label">邮箱：</div>
          <el-input v-model="channelform.dispatchEmail" clearable />
        </el-form-item>
        <el-form-item
          v-if="
            channelform.countryId &&
              ['329', '332', '339'].includes(channelform.countryId)
          "
          prop="dispatchProvince"
        >
          <div slot="label">州/省：</div>
          <el-select
            v-model="channelform.dispatchProvince"
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in stateMap[channelform.countryId]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-else prop="dispatchProvince">
          <div slot="label">州/省：</div>
          <el-input v-model="channelform.dispatchProvince" clearable />
        </el-form-item>
        <el-form-item prop="dispatchCity">
          <div slot="label">城市：</div>
          <el-input v-model="channelform.dispatchCity" clearable />
        </el-form-item>

        <el-form-item prop="dispatchZipCode">
          <div slot="label">邮编：</div>
          <el-input
            v-model="channelform.dispatchZipCode"
            clearable
            @input="changeZipCode"
          />
        </el-form-item>
        <el-form-item prop="dispatchAddress">
          <div slot="label">详细地址：</div>
          <el-input v-model="channelform.dispatchAddress" clearable />
        </el-form-item>
        <el-form-item prop="dispatchAddress2">
          <div slot="label">详细地址2：</div>
          <el-input v-model="channelform.dispatchAddress2" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="text" @click="getUserAddress">
            常用派送地址
          </el-button>
          <el-button type="text" @click="saveUserAddress">
            保存为常用派送地址
          </el-button>
        </el-form-item>
      </div>

      <!-- 详细地址 -->
      <el-form-item
        v-if="
          orderType !== 'quickOrder' && channelform.purposeWarehouseType !== 700
        "
        prop="dispatchAddressCode"
      >
        <div slot="label">派送地址：</div>

        <!-- <el-tooltip
          class="item"
          content="请先选择目的国家与仓库类型"
          effect="light"
          placement="top-end"
        > -->
        <el-select
          v-model="channelform.dispatchAddressCode"
          filterable
          placeholder="请选择"
          @change="changeDetailedAddress"
        >
          <template v-if="channelform.purposeWarehouseType !== 400">
            <el-option
              v-for="item in addressList"
              :key="item.id"
              :label="`${item.address}${
                item.address2 ? ' ' + item.address2 : ''
              },${item.city},${item.province},${item.zipCode}(${item.fbaCode})`"
              :value="item.fbaCode"
            />
          </template>
          <template v-else>
            <el-option
              v-for="item in addressList"
              :key="item.id"
              :label="`${item.fbaCode}`"
              :value="item.fbaCode"
            />
          </template>
        </el-select>
        <!-- </el-tooltip> -->
      </el-form-item>
      <div v-if="[700, 800].includes(channelform.purposeWarehouseType)">
        <el-form-item prop="deliveryNumber">
          <div slot="label">入仓号/入仓预约链接：</div>
          <el-input v-model="channelform.deliveryNumber" clearable />
        </el-form-item>
        <el-form-item prop="deliveryFiles">
          <div slot="label">派送文件：</div>

          <el-upload
            ref="upload"
            class="upload-demo"
            action="#"
            :show-file-list="false"
            :auto-upload="true"
            :http-request="uploadDeliveryFiles"
          >
            <el-button slot="trigger" size="small" type="primary">
              选取文件
            </el-button>
            <!-- <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过500kb
          </div> -->
          </el-upload>
          <div
            v-if="
              channelform.deliveryFilesMap &&
                Object.values(channelform.deliveryFilesMap).length > 0
            "
          >
            <template v-for="(val, key) in channelform.deliveryFilesMap">
              <el-row :key="val">
                <el-col :span="20">
                  <i class="el-icon-document" />
                  <span>{{ key }}</span>
                </el-col>
                <el-col :span="4" class="text-right">
                  <i
                    class="el-icon-close pointer"
                    @click="removeFile('deliveryFilesMap', key)"
                  />
                </el-col>
              </el-row>
            </template>
          </div>
        </el-form-item>
      </div>
      <!-- 渠道能力 -->
      <el-form-item prop="channelCapacity">
        <div slot="label">渠道能力：</div>

        <el-checkbox-group v-model="channelform.channelCapacity">
          <el-checkbox
            v-for="(item, value) in publicData.channelAbilitysMap"
            :key="value"
            :label="value"
            name="channelCapacity"
            @change="checkChannelSearchCriteria"
          >
            {{ item }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <!-- 特殊产品 -->
      <el-form-item prop="specialProduct">
        <div slot="label">特殊产品：</div>

        <el-checkbox-group
          v-model="channelform.specialProduct"
          @change="changeSpecialProductOptions"
        >
          <el-checkbox
            v-if="publicData.specialProductsMap[53]"
            label="53"
            :disabled="disabledSpecialProduct1"
            name="specialProduct"
          >
            均不是
          </el-checkbox>
          <template v-for="(item, value) in publicData.specialProductsMap">
            <template v-if="item !== '均不是'">
              <el-checkbox
                :key="value"
                :label="value"
                :disabled="disabledSpecialProduct2"
                name="specialProduct"
              >
                {{ item }}
              </el-checkbox>
            </template>
          </template>
        </el-checkbox-group>
      </el-form-item>

      <!-- 是否包税 -->
      <el-form-item prop="isTaxFarming">
        <div slot="label">是否包税：</div>

        <el-radio-group
          v-model="channelform.isTaxFarming"
          @change="changeTaxFarming"
        >
          <el-radio :disabled="isTaxFarmingDisabled[0]" :label="parseInt(1)">
            是
          </el-radio>
          <el-radio :disabled="isTaxFarmingDisabled[1]" :label="parseInt(0)">
            否
          </el-radio>
        </el-radio-group>
        <el-tooltip
          class="item"
          content="您是否选择我司的包税渠道？"
          effect="light"
          placement="right"
        >
          <i class="el-icon-question icon-question text-yellow" />
        </el-tooltip>
      </el-form-item>

      <!-- 交货条款 -->
      <el-form-item prop="deliveryTerms">
        <div slot="label">交货条款：</div>

        <el-radio-group
          v-model="channelform.deliveryTerms"
          @change="changeDelivery"
        >
          <el-radio :disabled="termsOfDeliveryDisabled[0]" label="DDP">
            DDP
          </el-radio>
          <el-radio :disabled="termsOfDeliveryDisabled[1]" label="DDU">
            DDU
          </el-radio>
        </el-radio-group>
        <el-tooltip class="item" effect="light" placement="right">
          <div slot="content">
            DDU：是指您在目的国自有进口商，且在目的国自行支付关税（即：关税到付）；
            <br>DDP：是指您在目的国自有或者无进口商，需我司先行垫付关税（即：关税预付）；
            <br>如您选择我司的包税渠道，则交货条款默认DDP
          </div>
          <i class="el-icon-question icon-question text-yellow" />
        </el-tooltip>
      </el-form-item>

      <!-- 是否报关 -->
      <el-form-item prop="isCustomerDeclaration">
        <div slot="label">是否报关：</div>

        <el-radio-group
          v-model="channelform.isCustomerDeclaration"
          @change="changeCustomerDeclaration"
        >
          <el-radio :label="parseInt(0)" class="margin-left"> 否 </el-radio>
          <el-radio :label="parseInt(1)"> 是 </el-radio>
          <!-- <el-radio :label="1">是</el-radio> -->
          <!-- <el-radio :label="0">否</el-radio> -->
        </el-radio-group>
        <el-tooltip class="item" effect="light" placement="right">
          <div slot="content">
            是指您指定用某一家具有进出口权的公司做出口申报，能自行提供整套报关单证，且后续要做出口退税的情况。请选择是。如非此情况，请选择否。
          </div>
          <i class="el-icon-question icon-question text-yellow" />
        </el-tooltip>
      </el-form-item>
      <el-form-item v-if="channelform.isCustomerDeclaration" prop="channel">
        <div slot="label">报关资料上传：</div>

        <el-upload
          ref="upload"
          class="upload-demo"
          action="#"
          :show-file-list="false"
          :auto-upload="true"
          :http-request="uploadExtraAttributes"
        >
          <el-button slot="trigger" size="small" type="primary">
            选取文件
          </el-button>
          <!-- <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过500kb
          </div> -->
        </el-upload>
        <div
          v-if="
            channelform.extraAttributes &&
              Object.values(channelform.extraAttributes).length > 0
          "
        >
          <template v-for="(val, key) in channelform.extraAttributes">
            <el-row :key="val">
              <el-col :span="20">
                <i class="el-icon-document" />
                <span>{{ key }}</span>
              </el-col>
              <el-col :span="4" class="text-right">
                <i
                  class="el-icon-close pointer"
                  @click="removeFile('extraAttributes', key)"
                />
              </el-col>
            </el-row>
          </template>
        </div>
      </el-form-item>
      <!-- 渠道 -->
      <el-form-item prop="inStockChannel">
        <div slot="label">渠道：</div>

        <el-select
          v-model="channelform.inStockChannel"
          filterable
          placeholder="请选择"
          @change="changeChannelFn"
        >
          <el-option
            v-for="(item, value) in customerChannelMap"
            :key="value"
            :label="item"
            :value="parseInt(value)"
          />
        </el-select>
        <el-tooltip class="item" effect="light" placement="right">
          <div slot="content">
            {{
              channelform.inStockChannel
                ? '点击查看该渠道附加费和操作说明'
                : '请选择渠道'
            }}
          </div>
          <i
            class="el-icon-info icon-absolute text-red"
            @click="
              channelform.inStockChannel
                ? (dialogTips = true)
                : (dialogTips = false)
            "
          />
        </el-tooltip>
      </el-form-item>

      <template v-if="channelform.shippingWay === 'FCL'">
        <el-row v-for="(val, index) in boxMap" :key="index">
          <el-col :span="10">
            <el-form-item prop="cabinetNumber">
              <div slot="label">柜量：</div>
              <el-input
                v-model.number="val.cabinetNumber"
                type="number"
                min="0"
                clearable
                @blur="selectBox"
              />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item prop="cabinetType">
              <div slot="label" class="text-right">柜型：</div>
              <el-select
                v-model="val.cabinetType"
                filterable
                placeholder="请选择"
                @change="selectBox"
              >
                <el-option
                  v-for="item in publicData.cabinetTypeMap"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4" class="margin-top-xs">
            <el-link
              icon="el-icon-plus"
              :underline="false"
              class="margin-lr-xl"
              @click="onAdd(val)"
            />
            <el-link
              icon="el-icon-minus"
              :underline="false"
              @click.prevent="removeDomain(val)"
            />
          </el-col>
        </el-row>
      </template>

      <!-- 派送方式 -->
      <el-form-item
        v-if="
          publicData.countryMap &&
            channelform.inStockChannel &&
            publicData.channelMap[channelform.inStockChannel] &&
            publicData.channelMap[channelform.inStockChannel].indexOf(
              '美国整柜'
            ) != -1
        "
        prop="deliveryType"
      >
        <div slot="label">派送方式：</div>

        <el-select
          v-model="channelform.deliveryType"
          filterable
          placeholder="请选择"
        >
          <el-option label="整柜直送" :value="parseInt(0)" />
          <el-option label="拆柜派送" :value="parseInt(1)" />
        </el-select>
      </el-form-item>

      <!-- 国内分区 -->
      <el-form-item prop="provinceId">
        <div slot="label">国内分区：</div>

        <el-select
          v-model="channelform.provinceId"
          filterable
          clearable
          :disabled="true"
          :placeholder="tipsText ? tipsText : '请选择'"
          @change="changeProvinceId"
        >
          <el-option
            v-for="(item, value) in provinceNameAndIdMap"
            :key="value"
            :label="item"
            :value="value"
          />
        </el-select>
      </el-form-item>

      <!-- PVA -->
      <el-form-item
        v-if="
          createTpye !== 'OrderToExpressDelivery'&&
            publicData.countryMap &&
            channelform.countryId &&
            publicData.countryMap[channelform.countryId] &&
            publicData.countryMap[channelform.countryId].indexOf('英国') != -1 &&
            channelform.inStockChannel &&
            channelform.isTaxFarming === 0 &&
            (channelform.purposeWarehouseType === 100 ||
              channelform.purposeWarehouseType === 400)
        "
        prop="isPVA"
        label-width="250px"
      >
        <div slot="label">Postponed VAT Accounting/增值税递延：</div>

        <el-radio-group v-model="channelform.isPVA">
          <el-radio :label="parseInt(1)">是</el-radio>
          <el-radio :label="parseInt(0)">否</el-radio>
        </el-radio-group>
        <el-tooltip class="item" effect="light" placement="right">
          <div slot="content">
            <div style="padding: 5px 10px">
              进口增值税延迟核算 Postponed VAT
              accounting，即您无需在清关时先支付进口增值税（import
              VAT），再抵扣。直接在季度申报时包括这方面数据即可。
              <br>
              详情请查看：
              <a
                href="https://www.gov.uk/guidance/check-when-you-can-account-for-import-vat-on-your-vat-return"
                target="_blank"
              >
                HMRC官网
              </a>
            </div>
          </div>

          <i class="el-icon-question icon-question text-yellow" />
        </el-tooltip>
      </el-form-item>

      <el-row class="text-row">
        <el-col :span="13">
          <el-form-item>
            <div slot="label">预计计费重：</div>
            <span>{{ finalWeight }}</span>
          </el-form-item>
        </el-col>
        <el-col v-if="isCheckPrice" :span="11" class="text-tips">
          <el-form-item class="text-right">
            <div slot="label">预计运费:</div>
            <span>{{ feightMoney }}</span>
            <el-tooltip class="item" effect="light" placement="right">
              <div slot="content">
                该运费仅供参考，实际收费以我司入仓数据为计费标准
              </div>
              <i class="el-icon-info icon-question text-red" />
            </el-tooltip>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 中澳证 -->
      <el-form-item
        v-if="
          publicData.countryMap &&
            channelform.countryId == 339 &&
            channelform.isTaxFarming === 0
        "
        prop="isChinaAustraliaCard"
        label-width="120px"
      >
        <div slot="label">委托制作中澳证：</div>

        <el-radio-group v-model="channelform.isChinaAustraliaCard">
          <el-radio :label="parseInt(1)">是</el-radio>
          <el-radio :label="parseInt(0)">否</el-radio>
        </el-radio-group>
        <el-tooltip class="item" effect="light" placement="right">
          <div slot="content">
            <div style="padding: 5px 10px">
              是否要花费150RMB由九方代做一份中澳证以免目的港的DUTY税费
            </div>
          </div>

          <i class="el-icon-question icon-question text-yellow" />
        </el-tooltip>
      </el-form-item>
      <el-row>
        <el-col :xs="24" :sm="24" :md="24" :lg="13" class="md-100">
          <el-form-item prop="selfDelivered">
            <div slot="label">交货方式：</div>

            <el-radio-group v-model="channelform.selfDelivered">
              <el-radio :label="parseInt(1)">九方提货</el-radio>
              <el-radio :label="parseInt(0)">客户自送</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="11" class="md-100">
          <el-form-item prop="isBuyInsurance">
            <div slot="label">是否购买保险：</div>

            <el-radio-group v-model="channelform.isBuyInsurance">
              <el-popover
                placement="top"
                width="400"
                trigger="hover"
                class="margin-rigth"
              >
                <div>赔偿细则和标准：</div>
                <div>
                  1、甲方按照（产品采购货值+运费）的 0.3%向乙方支付保费；
                </div>
                <div>2、按照系统下单时提供的（产品采购货值+运费）赔偿；</div>
                <div>3、无免赔，即按照产品采购货值+运费的 100%赔偿；</div>
                <div class="text-red">
                  4、赔偿上限：空运及快递为RMB 800/KG，最高RMB 200万/票；
                  海运拼箱RMB 100万/票，整柜RMB 200万/柜。
                </div>

                <el-radio slot="reference" :label="1">
                  <span class="margin-right">是</span>
                </el-radio>
              </el-popover>
              <el-popover placement="top" width="400" trigger="hover">
                <div>赔偿细则和标准：</div>
                <div>1、按照系统下单时提供的（产品采购货值+运费）赔偿；</div>
                <div>
                  2、免赔额为 10%，即只赔偿（产品采购货值+运费）的 90%；
                </div>
                <div class="text-red">
                  3、赔偿上限：空运及快递为RMB 200/KG，最高RMB 50万/票；
                  海运拼箱RMB 10万/票，整柜RMB 50万/柜。
                </div>

                <el-radio slot="reference" :label="0">否</el-radio>
              </el-popover>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="text-gray margin-bottom-sm">
        如送货不在预计入仓时间段内，需提前联系对应销售，通知仓库做收货准备
      </div>

      <el-form-item prop="etInStock">
        <div slot="label">入仓时间：</div>
        <el-row>
          <el-col :span="12">
            <el-date-picker
              v-model="etInStockDay"
              type="date"
              placeholder="选择日期"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd"
              style="width: 100%"
              :editable="false"
              @change="changeEtInStockDay"
            />
          </el-col>
          <el-col :span="12">
            <!-- <el-form-item prop="etInStockTime"> -->
            <el-select
              v-model="etInStockTime"
              placeholder="请选择时间段"
              @change="changeEtInStock"
            >
              <el-option
                v-for="item in timeOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
            <!-- </el-form-item> -->
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item prop="customerRemark">
        <div slot="label">备注：</div>
        <el-input
          v-model="channelform.customerRemark"
          type="textarea"
          clearable
        />
      </el-form-item>
    </el-form>

    <el-dialog :visible.sync="dialogTips" title="渠道附加费和操作说明">
      <div v-html="channelTips" />
    </el-dialog>

    <el-dialog title="选择常用派送地址" :visible.sync="selectShippingAddress">
      <div id="dialogMain" class="dialog-main">
        <el-card
          v-for="(item, index) in pickupInfo"
          :key="index"
          class="card-main"
          :class="{ selectCart: item.selectType }"
        >
          <el-form
            label-position="left"
            label-width="98px"
            size="mini"
            @click.native="selectCard(index)"
            @dblclick.native="selectedCard(index)"
          >
            <el-row>
              <el-col :xs="20" :sm="20" :md="20" :lg="20">
                <el-form-item prop="importerCompany">
                  <div slot="label">公司名/个人：</div>
                  <span>{{ item.customerDeliveryCompany }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :md="12" :lg="8">
                <el-form-item>
                  <div slot="label">联系人:</div>
                  <span>{{ item.customerDeliveryAddressAttn }}</span>
                </el-form-item>
              </el-col>
              <el-col :md="12" :lg="8">
                <el-form-item>
                  <div slot="label">电话:</div>
                  <span>{{ item.customerDeliveryAddressPhone }}</span>
                </el-form-item>
              </el-col>
              <el-col :md="12" :lg="8">
                <el-form-item>
                  <div slot="label">城市:</div>
                  <span>{{ item.city }}</span>
                </el-form-item>
              </el-col>
              <el-col :md="12" :lg="8">
                <el-form-item>
                  <div slot="label">省:</div>
                  <span>{{ item.state }}</span>
                </el-form-item>
              </el-col>
              <el-col :md="12" :lg="8">
                <el-form-item>
                  <div slot="label">邮编:</div>
                  <span>{{ item.zipCode }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item>
              <div slot="label">地址1:</div>
              <span>{{ item.address }}</span>
            </el-form-item>
            <el-form-item>
              <div slot="label">地址2:</div>
              <span>{{ item.address2 }}</span>
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="selectShippingAddress = false">
          取消
        </el-button>
        <el-button type="primary" @click="selectCustomerdeliveryaddress">
          确 定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="请注意" width="30%" :visible.sync="dialogVisibleJp">
      <div class="margin-bottom">
        请注意，根据日本海关新规，提供的截图需规范才能目的港正常清关。为保证您的时效，请上传正确的截图。<br>
      </div>
      <div>
        截图规范，详见清关发票处
        <a
          class="text-blue"
          href="./excel/japan_customs_document_requirement.xls"
        >
          日本海关文件要求
        </a>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { getFindKey } from '@/utils'
import { getState } from '@/utils/getState'
import { queryState } from '@/api/public'
import { clone } from '@/utils/clone'
import {
  customerdeliveryaddressList,
  customerdeliveryaddressSave
} from '@/api/myProfile'
import {
  queryFbaCodeByCoutry,
  queryInStockChannel,
  uploadWaybillFile,
  queryMatchProvince
} from '@/api/waybill'
import { isNoEmptyObject } from '@/utils/waybill-public'
export default {
  name: 'SelectChannelLeft',
  props: {
    orderType: {
      type: String,
      default: 'quickOrder'
    },
    channelFormLeft: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return (
            time.getTime() < Date.now() - 3600 * 1000 * 24 ||
            time.getDay() === 0
          )
        }
      },
      stateMap: getState(),
      fileList: [],
      boxMap: [{ cabinetNumber: '', cabinetType: '' }],
      dialogVisibleJp: false,
      disabledSpecialProduct1: false, // 特殊产品禁用
      disabledSpecialProduct2: false, // 特殊产品禁用
      isDisabledProvinceId: false, //  禁选国内分区
      finalWeight: 0, //  预计计费重
      feightMoney: 0, //  预计 运费
      selectShippingAddress: false,
      dialogTips: false,
      isTaxFarmingDisabled: [false, false],
      termsOfDeliveryDisabled: [false, false],
      addressList: [],
      zipCode: '',
      customerChannelMap: {},
      customerChannelForm: {},
      provinceNameAndIdMap: {},
      pickupInfo: [], //  派送地址
      channelform: {
        // cabinetNumber: '', // 柜量
        // cabinetType: '', // 柜型
        purposeWarehouseType: '', //  目的仓库类型
        customerRemark: '', // 运单备注
        //  value: '',
        loadingPort: '', // 起运地
        countryId: '', //  国家
        customerActualWeight: '', //  重量
        customerTotalPackages: '', // 件数
        customerVolume: '', //  体积
        dispatchAddressCode: '', // 地址
        channelCapacity: [], //  渠道能力
        specialProduct: [], //  特殊产品
        isTaxFarming: '', // 是否包税
        deliveryTerms: '', //  交货条款
        isCustomerDeclaration: '', //  是否报关
        provinceId: '', //  国内分区
        inStockChannel: '', //  渠道
        deliveryType: '', // 派送方式
        selfDelivered: '', // 提货方式
        isChinaAustraliaCard: '', // 提货方式
        isBuyInsurance: 0, // 保险
        dispatcher: '', // 公司名/个人
        dispatchLinkMan: '', //  联系人
        dispatchPhone: '', //  联系电话
        dispatchEmail: '', //  联系电话
        dispatchProvince: '', //  省
        dispatchCity: '', //  城市
        dispatchZipCode: '', //  邮编
        dispatchAddress: '', //  地址
        dispatchAddress2: '', //  地址2
        shippingWay: '', //  海空运下单方式
        isPVA: '', //  Postponed VAT Accounting/增值税递延
        extraAttributes: {}, // 上传文件路径
        expectFreight: 0, // 预计运费
        customerChargedWeight: 0, // 客户预报计费重
        etInStock: '',
        deliveryNumber: '',
        deliveryFiles: [],
        deliveryFilesMap: {}
      },
      etInStockDay: '',
      etInStockTime: '',
      timeOptions: [
        '09:00-11:00',
        '11:00-13:00',
        '13:00-15:00',
        '15:00-17:00',
        '17:00-19:00',
        '19:00-21:00'
      ],
      channelTips: '请选择渠道',
      rules: {
        loadingPort: [
          { required: true, message: '请选择起运地', trigger: 'change' }
        ],
        countryId: [
          { required: true, message: '请选择目的国家', trigger: 'change' }
        ],
        dispatchAddressCode: [
          { required: true, message: '请选择详细地址', trigger: 'change' }
        ],
        customerActualWeight: [
          { required: true, message: '请填写正整数', trigger: 'blur' },
          {
            pattern: /^[+]?\d*\.?\d{0,3}$/,
            message: '须为数字,可留3位小数'
          }
        ],
        customerVolume: [
          { required: false, message: '请填写正整数', trigger: 'blur' },
          {
            pattern: /^[+]?\d*\.?\d{0,3}$/,
            message: '须为数字,可留3位小数'
          }
        ],
        customerTotalPackages: [
          { required: true, message: '请填写正整数', trigger: 'blur' },
          { type: 'number', message: '件数必须为数字值' }
        ],
        purposeWarehouseType: [
          { required: true, message: '请选择仓库类型', trigger: 'change' }
        ],
        // cabinetNumber: [
        //   { required: true, message: '请填写正整数', trigger: 'blur' },
        //   { type: 'number', message: '必须为数字值' }
        // ],
        isPVA: [{ required: true, message: '请选择PVA', trigger: 'change' }],
        // cabinetType: [
        //   { required: true, message: '请选择柜型', trigger: 'change' }
        // ],

        channelCapacity: [
          {
            type: 'array',
            required: true,
            message: '请至少选择一个',
            trigger: 'change'
          }
        ],
        specialProduct: [
          {
            type: 'array',
            required: true,
            message: '请至少选择一个',
            trigger: 'change'
          }
        ],
        isTaxFarming: [
          { required: true, message: '请选择是否包税', trigger: 'change' }
        ],
        deliveryTerms: [
          { required: true, message: '请选择交货条款', trigger: 'change' }
        ],
        isCustomerDeclaration: [
          { required: true, message: '请选择是否报关', trigger: 'change' }
        ],
        inStockChannel: [
          { required: true, message: '请选择渠道', trigger: 'change' }
        ],
        deliveryType: [
          { required: true, message: '请选择派送方式', trigger: 'change' }
        ],
        provinceId: [
          { required: false, message: '请选择国内分区', trigger: 'change' }
        ],
        isChinaAustraliaCard: [
          {
            required: true,
            message: '请选择是否委托制作中澳证',
            trigger: 'change'
          }
        ],
        selfDelivered: [
          { required: true, message: '请选择提货方式', trigger: 'change' }
        ],
        isBuyInsurance: [
          { required: true, message: '请选择是否购买保险', trigger: 'change' }
        ],
        dispatcher: [
          { required: true, message: '请填写公司名', trigger: 'blur' }
          // {
          //   pattern: /^[a-zA-Z0-9_\,\.\/\-\s\!\@\#\$\%\^\&\*\(\)]*$/,
          //   message: '请填写英文或者数字'
          // }
        ],

        dispatchLinkMan: [
          { required: true, message: '请填写联系人', trigger: 'blur' }
        ],
        dispatchPhone: [
          { required: true, message: '请填写联系方式', trigger: 'blur' }
        ],
        dispatchEmail: [
          { required: true, message: '请填写邮箱地址', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],

        dispatchAddress: [
          { required: true, message: '请填写地址', trigger: 'blur' },
          {
            min: 1,
            max: 35,
            message: '长度在 1 到 35 个字符',
            trigger: 'blur'
          }
        ],
        dispatchAddress2: [
          { required: false, message: '请填写地址', trigger: 'blur' },
          {
            min: 1,
            max: 30,
            message: '长度在 1 到 30 个字符',
            trigger: 'blur'
          }
        ],
        dispatchProvince: [
          { required: true, message: '请填写省', trigger: 'change' }
        ],
        dispatchCity: [
          { required: true, message: '请填写城市', trigger: 'change' }
        ]
        // etInStock: [
        //   { required: true, message: '请选择日期', trigger: 'change' }
        // ]
      },
      tipsText: '',
      timer: null,
      timer2: null
    }
  },
  computed: {
    ...mapGetters(['createTpye', 'publicData', 'isCheckPrice']),
    isJapan() {
      return (
        this.publicData.countryMap &&
        this.channelform.countryId &&
        this.publicData.countryMap[this.channelform.countryId] &&
        this.publicData.countryMap[this.channelform.countryId].indexOf(
          '日本'
        ) != -1
      )
    }
  },
  watch: {
    channelform: {
      handler(newVal, oldVal) {
        //  FBA 快捷下单 默认仓库为FBA
        if (this.orderType === 'quickOrder') {
          newVal.purposeWarehouseType = 100
        }
        this.$store.dispatch('createWaybill/changeChannelFormLeft', newVal)
        this.$emit('update:channelFormLeft', newVal)
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    if (sessionStorage.getItem('channelFormLeft')) {
      const data = JSON.parse(sessionStorage.getItem('channelFormLeft'))
      Object.assign(this.channelform, data)
    }
  },
  mounted() {
    if (this.createTpye === 'orderToSeaFreight') {
      this.rules.customerVolume[0].required = true
    }
    const _this = this
    // 特定邮编
    this.rules.dispatchZipCode = [
      { required: true, message: '请填写邮编' },
      {
        validator: (rule, value, cb) => {
          const reg1 = /^((\d{5})*(-\d{4})|(\d{5}))$/
          const val = value.toString()
          if (
            parseFloat(_this.channelform.countryId) === 329 &&
            !reg1.test(val)
          ) {
            cb(new Error('格式错误，美国邮编请填入XXXXX或者XXXXX-XXXX'))
          } else {
            cb()
          }
        },
        trigger: 'blur'
      }
    ]
    //  this.$store.dispatch('createWaybill/changeChannelFormLeft', this.channelform)
  },
  methods: {
    // 查询 州/省
    async queryStateInfo() {
      console.log('查询 州/省 :>> ')
      const data = await queryState({
        id: parseInt(this.channelform.countryId)
      })
      console.log('data :>> ', data)
    },
    selectBox() {
      this.$emit('func', this.boxMap)
    },
    // 改变分区
    changeProvinceId(val) {
      console.log('val :>> ', val)
      if (!val) {
        this.$message.error('无分区，已为您选择渠道相应运费')
        this.feightMoney =
          this.customerChannelFormMap[this.channelform.inStockChannel]
            .feightMoney || 0
        return
      }
      this.feightMoney =
        this.customerChannelForm.partitionAndCost[
          this.provinceNameAndIdMap[val]
        ] || 0

      this.channelform.expectFreight = this.feightMoney

      let flag = false
      for (const i in this.customerChannelForm.partitionAndCost) {
        if (this.customerChannelForm.partitionAndCost[i]) {
          flag = true
        }
      }

      if (flag) {
        if (!this.feightMoney) {
          this.$message.error('该分区无相应运费，请重新选择')
        }
      } else {
        if (!this.customerChannelForm.feightMoney) {
          this.$message.error('该渠道与分区无相应运费，请重新选择渠道')
        }
        this.tipsText = '渠道无该分区价格，请找客服单询'
      }
    },
    changeCustomerDeclaration(val) {
      this.$delete(this.channelform, 'isCustomerDeclaration')
      this.$set(this.channelform, 'isCustomerDeclaration', val)
      this.checkChannelSearchCriteria()
    },
    onAdd(val) {
      if (val.cabinetNumber && val.cabinetType) {
        this.boxMap.push({ cabinetNumber: '', cabinetType: '' })
      } else {
        this.$message.error('请先填写当前柜型柜量再新增')
      }
    },
    removeDomain(val) {
      const index = this.boxMap.indexOf(val)
      if (index !== -1 && this.boxMap.length > 1) {
        this.boxMap.splice(index, 1)
      }
    },
    handleRemove(file, fileList) {},
    beforeUpload(file) {
      this.fileList.push(file)
      return false
    },
    //  改变 特殊产品
    changeSpecialProductOptions(e) {
      console.log('e :>> ', e)
      if (e[e.length - 1] === '53') {
        this.channelform.specialProduct = ['53']
        this.disabledSpecialProduct1 = false
        this.disabledSpecialProduct2 = true
      } else {
        const index = this.channelform.specialProduct.indexOf('53')
        if (index > -1) {
          this.channelform.specialProduct.splice(index, 1)
        }
        this.disabledSpecialProduct1 = true
        this.disabledSpecialProduct2 = false
      }
      if (e.length === 0) {
        this.disabledSpecialProduct1 = false
        this.disabledSpecialProduct2 = false
      }

      this.checkChannelSearchCriteria()
    },
    //  改变 是否包税
    changeTaxFarming(e) {
      console.log('createTpye', this.createTpye)
      // 澳大利亚
      if (
        !this.channelform.isChinaAustraliaCard &&
        Number(this.channelform.countryId) === 339 &&
        this.channelform.isTaxFarming === 0
      ) {
        this.$set(this.channelform, 'isChinaAustraliaCard', 0)
      }
      //  不包税: "38"
      //  包税: "32"
      //  包税时，只可以选择DDP
      if (parseInt(e) === 1) {
        // this.channelform.isVatAndEori = 0
        // this.$set(this.channelform, 'isVatAndEori', 0)
        this.$set(this.channelform, 'isPVA', '')
        this.$set(this.channelform, 'deliveryTerms', 'DDP')
        this.$set(this.termsOfDeliveryDisabled, 1, true)
      } else {
        // this.$set(this.channelform, 'isVatAndEori', 1)
        this.$set(this.termsOfDeliveryDisabled, 1, false)
      }
      this.checkChannelSearchCriteria()
    },
    //  改变 交货条款
    changeDelivery(e) {
      //  DDP: "29"
      //  DDU: "28"
      //  交货条款 === DDU 时，只可以选择不包税
      if (e === 'DDU') {
        this.$set(this.channelform, 'isTaxFarming', 0)
        this.$set(this.isTaxFarmingDisabled, 0, true)
      } else {
        this.$set(this.isTaxFarmingDisabled, 0, false)
      }
      this.checkChannelSearchCriteria()
    },

    /**
     * @description: 根据国家 跟 仓库 匹配 地址
     * @param { String } type 编辑回显时候传的参数
     * @return {*}
     */
    async retrieveAddress(type, num) {
      const cf = this.channelform

      this.finalWeight = 0 // 计费重
      this.feightMoney = 0 //  预计运费
      this.channelform.customerChargedWeight = 0
      this.channelform.expectFreight = 0
      //  var inStockChannel = cf.inStockChannel //  入库渠道
      //  if (!inStockChannel) {
      //    return
      //  }
      //  var dispatchAddressCode = cf.dispatchAddressCode
      //  if (!dispatchAddressCode) {
      //    return
      //  }
      if (
        cf.countryId &&
        cf.purposeWarehouseType &&
        cf.purposeWarehouseType !== 700
      ) {
        const data = await queryFbaCodeByCoutry({
          countryId: cf.countryId,
          stockType: cf.purposeWarehouseType
        })

        this.addressList = data.shippingFbaStocks
        const flag = false
        for (const i in this.addressList) {
          if (i === cf.dispatchAddressCode) {
            flag = true
          }
        }
        if (!flag && type === 'add') {
          console.log('清空派送地址 :>> 无匹配的派送地址')
          cf.dispatchAddressCode = ''
        }

        if (type === 'add') {
          this.checkChannelSearchCriteria()
        }
      }

      if (cf.purposeWarehouseType === 700) {
        console.log('私人地址 :>> ')
        cf.dispatchAddressCode = ''
        if (type === 'add') {
          this.checkChannelSearchCriteria()
        }
        console.log('cf.countryId :>> ', cf.countryId)
        if (cf.countryId) {
          this.queryStateInfo()
        }
      }

      // 日本
      if (this.isJapan && num === 0) {
        //
        this.dialogVisibleJp = true
      }
      // 澳大利亚
      if (
        !this.channelform.isChinaAustraliaCard &&
        Number(cf.countryId) === 339 &&
        cf.isTaxFarming === 0
      ) {
        this.$set(this.channelform, 'isChinaAustraliaCard', 0)
      }
    },
    //  改变体积
    changeCustomerVolume() {
      const reg = /^[+]?\d*\.?\d{0,3}$/
      if (
        this.channelform.customerVolume &&
        reg.test(this.channelform.customerVolume)
      ) {
        this.checkChannelSearchCriteria()
      }
    },
    //  查验渠道搜索条件
    //  DDP: "29"
    //  DDU: "28"
    //  不包税: "38"
    //  包税: "32"
    checkChannelSearchCriteria() {
      const cf = this.channelform
      console.log('cf :>> ', cf)
      const reg = /^[+]?\d*\.?\d{0,3}$/

      if (
        cf.loadingPort &&
        cf.countryId &&
        cf.customerActualWeight &&
        reg.test(cf.customerActualWeight) &&
        cf.channelCapacity.length > 0 &&
        cf.specialProduct.length > 0 &&
        cf.deliveryTerms !== '' &&
        cf.isTaxFarming !== ''
      ) {
        this.retrieveChannel()
      }
    },
    /**
     * @description: 查找渠道信息
     * @param {*} type 判断是否为 编辑
     * @return {*}
     */
    async retrieveChannel(type) {
      const cf = this.channelform
      let zipCode = ''
      const fbaStockCode =
        cf.purposeWarehouseType === 700 ? '' : cf.dispatchAddressCode
      if (fbaStockCode) {
        const t = this.addressList.find(
          (x) => x.fbaCode === cf.dispatchAddressCode
        )
        zipCode = t ? t.zipCode : ''
      } else {
        zipCode = cf.dispatchZipCode
      }

      if (this.orderType === 'quickOrder') {
        zipCode = cf.dispatchZipCode
      }

      const params = {
        channelLoadingPortId: parseInt(cf.loadingPort), //  起运地
        countryId: parseInt(cf.countryId), //  目的国家
        weight: parseFloat(cf.customerActualWeight), //  重量
        volumn: parseFloat(cf.customerVolume), //  体积
        channelAbility: cf.channelCapacity.toString(), //  渠道能力
        specialProduct: cf.specialProduct.toString(), //  特殊产品
        other: `${cf.deliveryTerms === 'DDP' ? 29 : 28},${
          cf.isTaxFarming ? 32 : 38
        }`, //  其他属性
        type: 1, //  客户渠道查询：0代表查询，1代表下单
        shipingWay:
          this.createTpye === 'OrderToAirFreight'
            ? 'ZX,AIR'
            : this.createTpye === 'orderToSeaFreight'
              ? 'FCL,LCL'
              : '99',
        fbaStockCode: fbaStockCode,
        zipCode: zipCode
      }
      //  return

      const data = await queryInStockChannel(params)
      if (!type) {
        this.finalWeight = 0 // 计费重
        this.feightMoney = 0 //  预计运费
        this.channelform.customerChargedWeight = 0
        this.channelform.expectFreight = 0
        this.customerChannelMap = [] //  渠道列表
        this.provinceNameAndIdMap = [] //  渠道信息列表
        cf.provinceId = '' //  国内分区
        cf.inStockChannel = '' //  渠道
        cf.shippingWay = ''
      }

      if (JSON.stringify(data) === '{}') {
        this.$message.error('没有符合的渠道，请重新选择')
        return
      }
      this.customerChannelMap = data.customerChannelMap
      this.customerChannelFormMap = data.customerChannelFormMap

      if (this.channelform.inStockChannel) {
        this.changeChannelFn(parseInt(this.channelform.inStockChannel))
      }
    },

    //  选择渠道
    async changeChannelFn(val) {
      console.log('val :>> ', val)
      this.tipsText = ''
      this.channelform.provinceId = ''
      const cf = this.channelform
      //  FBA快捷下单
      if (this.orderType === 'quickOrder') {
        console.log('cf.dispatchAddressCode :>> ', cf.dispatchAddressCode)
        if (!cf.dispatchAddressCode) {
          cf.inStockChannel = ''
          this.$message.error('请先上传入库计划装箱单')
          return
        }
      } else {
        // 标准下单
        //  判断是否有派送地址
        if (cf.purposeWarehouseType !== 700 && !cf.dispatchAddressCode) {
          cf.inStockChannel = ''
          this.$message.error('请选择派送地址')
          return
        }
        if (
          cf.purposeWarehouseType === 700 &&
          (!cf.dispatcher ||
            !cf.dispatchLinkMan ||
            !cf.dispatchPhone ||
            !cf.dispatchProvince ||
            !cf.dispatchCity ||
            !cf.dispatchZipCode ||
            !cf.dispatchAddress)
        ) {
          cf.inStockChannel = ''
          this.$message.error('请填写完整派送地址信息')
          return
        }
      }

      if (!val) {
        this.$message.error('请重新选择渠道,该渠道value值为空', 'danger')
        cf.inStockChannel = ''
        return
      }

      if (this.customerChannelFormMap[val]) {
        this.customerChannelForm = this.customerChannelFormMap[val]
        this.channelTips =
          this.customerChannelForm.customerChannel.channelExplain || '空'
        //
        cf.shippingWay =
          this.publicData.shippingWayMap[
            this.customerChannelFormMap[val].customerChannel.channelType
          ]

        console.log('cf.shippingWay :>> ', cf.shippingWay)
        //  渠道信息
        const map = this.customerChannelFormMap[val].provinceNameAndIdMap
        const p = {}
        for (const i in map) {
          p[map[i]] = i
        }
        this.provinceNameAndIdMap = p
        this.finalWeight = this.customerChannelForm.finalWeight
        this.channelform.customerChargedWeight =
          this.customerChannelForm.finalWeight
        // this.feightMoney = this.customerChannelFormMap[val].feightMoney
        console.log(
          'this.customerChannelForm.feightMoney :>> ',
          this.customerChannelForm.feightMoney
        )
      }
      let fbaCode = ''
      // 通过接口寻找默认分区

      const fbaStockCode =
        cf.purposeWarehouseType === 700 ? '' : cf.dispatchAddressCode
      const t = this.addressList.find(
        (x) => x.fbaCode === cf.dispatchAddressCode
      )
      const zipCode = !fbaStockCode ? cf.dispatchZipCode : t ? t.zipCode : ''
      const pid = await queryMatchProvince({
        countryId: Number(cf.countryId),
        instockChannelId: val,
        fbaStockCode: fbaStockCode,
        zipCode: zipCode
      })
      // 重组国内分区
      if (pid && JSON.stringify(pid) !== '{}') {
        this.isDisabledProvinceId = true
        // 如果存在默认分区
        const l = Object.keys(pid)

        this.provinceNameAndIdMap[l[0]] = pid[l[0]]
        cf.provinceId = l[0]

        const partitionAndCost = this.customerChannelForm.partitionAndCost //  分区运费信息
        if (pid[l[0]] in partitionAndCost) {
          const expectFreight = partitionAndCost[pid[l[0]]]

          this.feightMoney = expectFreight
          this.channelform.expectFreight = expectFreight
          return
        }
      } else if (
        val === 100 &&
        cf.dispatchAddressCode.indexOf('BHX4-') !== -1
      ) {
        this.isDisabledProvinceId = true
        if (!this.provinceNameAndIdMap['248']) {
          this.provinceNameAndIdMap['248'] = 'BHX4-CV5 9PF'
        }
        fbaCode = 'BHX4-CV5 9PF'
        cf.provinceId = '248'

        //  如果是英国海派-不包税=100   并且派送地址为BHX开头 分区默认选中BHX4
      } else if (val === 100 && cf.dispatchAddressCode.indexOf('BHX4') !== -1) {
        this.isDisabledProvinceId = true

        if (!this.provinceNameAndIdMap['231']) {
          this.provinceNameAndIdMap['231'] = 'BHX4'
        }
        fbaCode = 'BHX4'
        cf.provinceId = '231'

        //  如果是英国海派-不包税=100   并且派送地址为BHX开头 分区默认选中BHX4
      } else if (val === 85 && cf.dispatchAddressCode.indexOf('DTM2') !== -1) {
        //  如果是德国海派-不包税=85   并且派送地址为DTM开头 分区默认选中DTM2
        this.isDisabledProvinceId = true
        this.provinceNameAndIdMap['198'] = 'DTM2'
        fbaCode = 'DTM2'
        cf.provinceId = '198'
      } else if (val === 253 && cf.purposeWarehouseType !== 100) {
        fbaCode = '加拿大海外仓'
        cf.provinceId = '344'
      }

      console.log('fbaCode :>> ', fbaCode)

      if (fbaCode) {
        this.feightMoney =
          this.customerChannelForm.partitionAndCost[fbaCode] || 0
        this.channelform.expectFreight = this.feightMoney
        if (!this.feightMoney) {
          this.$message.error('该分区无相应运费，请重新选择')
          this.isDisabledProvinceId = false
        }
        return
      }

      if (cf.purposeWarehouseType === 700 && cf.dispatchZipCode) {
        const zipCodeStartStr = cf.dispatchZipCode.substr(0, 1)
        let dispatchAddressCode = ''
        if (
          zipCodeStartStr === '0' ||
          zipCodeStartStr === '1' ||
          zipCodeStartStr === '2' ||
          zipCodeStartStr === '3'
        ) {
          dispatchAddressCode = '邮编0、1、2、3开头'
        } else if (
          zipCodeStartStr === '4' ||
          zipCodeStartStr === '5' ||
          zipCodeStartStr === '6' ||
          zipCodeStartStr === '7'
        ) {
          dispatchAddressCode = '邮编4、5、6、7开头'
        } else if (zipCodeStartStr === '8' || zipCodeStartStr === '9') {
          dispatchAddressCode = '邮编8、9开头'
        }
        console.log('dispatchAddressCode :>> ', dispatchAddressCode)

        cf.provinceId =
          this.customerChannelForm.provinceNameAndIdMap[dispatchAddressCode] ||
          ''
        cf.provinceId = cf.provinceId.toString()
        this.feightMoney =
          this.customerChannelForm.partitionAndCost[dispatchAddressCode] || 0
        this.channelform.expectFreight = this.feightMoney
        if (cf.provinceId && !this.feightMoney) {
          this.$message.error('该分区无相应运费，请重新选择')
        }
        return
        // this.customerChannelForm.partitionAndCost[dispatchAddressCode]
      }

      console.log('this.provinceNameAndIdMap :>> ', this.provinceNameAndIdMap)
      console.log('cf :>> ', cf)
      this.calcFbaExpectFreight()
    },

    //  获取常用派送地址 并展示
    async getUserAddress() {
      if (!this.channelform.countryId) {
        this.$message.error('请选择目的国家！')
        return
      }
      const data = await customerdeliveryaddressList({
        authorization: getToken()
      })

      this.pickupInfo = data.filter(
        (x) => x.countryId === parseInt(this.channelform.countryId)
      )
      this.selectShippingAddress = true
      // console.log('this.pickupInfo', this.pickupInfo)
    },
    //  保存填写的地址信息
    async saveUserAddress() {
      console.log('触发保存 地址信息:>> ')
      const c = {
        countryId: this.channelform.countryId,
        customerDeliveryCompany: this.channelform.dispatcher,
        customerDeliveryAddressAttn: this.channelform.dispatchLinkMan,
        customerDeliveryAddressPhone: this.channelform.dispatchPhone,
        customerDeliveryAddressEmail: this.channelform.dispatchEmail,
        address: this.channelform.dispatchAddress,
        address2: this.channelform.dispatchAddress2,
        city: this.channelform.dispatchCity,
        state: this.channelform.dispatchProvince,
        zipCode: this.channelform.dispatchZipCode
      }
      // console.log('saveUserAddress :>> ', c)
      const r = {
        customerDeliveryCompany: '请填写收件人/公司名',
        customerDeliveryAddressAttn: '请填写联系人',
        customerDeliveryAddressPhone: '请填写联系电话',
        address: '请填写详细地址',
        city: '请填写城市',
        state: '请填写州/省',
        countryId: '请选择目的国家',
        zipCode: '请填写邮编'
      }
      // console.log('saveUserAddress :>> ', c)
      for (const i in c) {
        // console.log(i)
        if (!c[i] && i !== 'address2' && i !== 'customerDeliveryAddressEmail') {
          console.log('r[i] :>> ', r[i])
          this.$message.error(r[i])
          return
        }
      }
      // console.log('saveUserAddress :>> ', c)
      this.$store.dispatch('app/toggleDialog', true)

      const data = await customerdeliveryaddressSave(c)
      if (data.code === 200) {
        this.$message({
          message: '保存成功',
          type: 'success'
        })
      } else {
        this.$message.error(data.message)
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    //  单击加效果
    selectCard(index) {
      const time = this.timer
      clearTimeout(time) //  首先清除计时器
      this.timer = setTimeout(() => {
        // console.log('单击', index)
        for (const i in this.pickupInfo) {
          if (parseInt(i) === index) {
            const flag = this.pickupInfo[index].selectType
              ? this.pickupInfo[index].selectType
              : false
            this.$set(this.pickupInfo[index], 'selectType', !flag)
          } else {
            this.pickupInfo[i].selectType = false
          }
        }
      }, 300) //  大概时间300ms
    },
    //  双击=> 选择该派送地址
    selectedCard(index) {
      // console.log('双击', index)
      const time = this.timer
      clearTimeout(time)

      this.selectShippingAddress = false

      this.channelform.dispatcher =
        this.pickupInfo[index].customerDeliveryCompany
      this.channelform.dispatchLinkMan =
        this.pickupInfo[index].customerDeliveryAddressAttn

      this.channelform.dispatchPhone =
        this.pickupInfo[index].customerDeliveryAddressPhone
      this.channelform.dispatchEmail =
        this.pickupInfo[index].customerDeliveryAddressEmail

      this.channelform.dispatchAddress = this.pickupInfo[index].address
      this.channelform.dispatchAddress2 = this.pickupInfo[index].address2

      this.channelform.dispatchCity = this.pickupInfo[index].city
      this.channelform.dispatchProvince = this.pickupInfo[index].state
      this.channelform.dispatchZipCode = this.pickupInfo[index].zipCode

      // console.log(this.selectedImporterInfo)
    },

    //  选择并展示常用派送地址
    selectCustomerdeliveryaddress() {
      let index = ''
      for (const i in this.pickupInfo) {
        if (this.pickupInfo[i].selectType) {
          index = i
        }
      }
      this.selectedCard(index)
    },

    //  更改派送地址 选择FBA仓库地址发生变化,计费重运费重新计算
    changeDetailedAddress(val) {
      console.log('val :>> ', val)
      this.checkChannelSearchCriteria()
      const cf = this.channelform
      this.finalWeight = 0 // 计费重
      this.feightMoney = 0 //  预计运费
      this.channelform.customerChargedWeight = 0
      this.channelform.expectFreight = 0
      if (!cf.inStockChannel) {
        return
      }
      if (!val) {
        return
      }

      if (
        cf.inStockChannel === 100 &&
        cf.dispatchAddressCode.indexOf('BHX4') !== -1
      ) {
        this.isDisabledProvinceId = true
        this.provinceNameAndIdMap['BHX4'] = 231
        cf.provinceId = '231'
        cf.dispatchAddressCode = 'BHX4'
        //  如果是英国海派-不包税=100   并且派送地址为BHX开头 分区默认选中BHX4
      } else if (
        cf.inStockChannel === 85 &&
        cf.dispatchAddressCode.indexOf('DTM2') !== -1
      ) {
        //  如果是德国海派-不包税=85   并且派送地址为DTM开头 分区默认选中DTM2
        this.isDisabledProvinceId = true
        this.provinceNameAndIdMap['DTM2'] = 198
        cf.provinceId = '198'
        cf.dispatchAddressCode = 'DTM2'
      }
      if (!this.customerChannelFormMap[cf.inStockChannel]) {
        return
      }
      console.log(
        'this.customerChannelFormMap :>> ',
        this.customerChannelFormMap
      )

      this.calcFbaExpectFreight()
    },

    /**
     * @description: 计算FBA预计运费
     * @param {*}
     * @return {*}
     */
    calcFbaExpectFreight() {
      this.feightMoney = 0
      this.channelform.expectFreight = 0
      // console.log('calcFbaExpectFreight :>> ', 'calcFbaExpectFreight')
      const cf = this.channelform
      console.log('cf.dispatchAddressCode :>> ', cf.dispatchAddressCode)

      this.finalWeight = this.customerChannelForm.finalWeight
      this.channelform.customerChargedWeight =
        this.customerChannelForm.finalWeight

      if (
        cf.dispatchAddressCode === undefined ||
        cf.dispatchAddressCode === '' ||
        cf.dispatchAddressCode === null
      ) {
        return
      }
      console.log('this.customerChannelForm :>> ', this.customerChannelForm)
      if (this.customerChannelForm === null) {
        return
      }

      if (this.orderType === 'quickOrder') {
        cf.purposeWarehouseType = 100
      }

      let expectFreight
      const countryName = this.publicData.countryMap[cf.countryId]
      let dispatchAddressCode = cf.dispatchAddressCode
      const partitionAndCost = this.customerChannelForm.partitionAndCost //  分区运费信息

      console.log('partitionAndCost :>> ', partitionAndCost)
      //  分区运费域为空,取国家运费
      if (partitionAndCost === null) {
        expectFreight = this.customerChannelForm.feightMoney
        //  无分区
        cf.provinceId = ''
        this.feightMoney = expectFreight
        this.channelform.expectFreight = expectFreight
        return
      }

      // let provinceId = this.publicData.countryStateProvinceMap[
      //   dispatchAddressCode
      // ]
      let provinceId = getFindKey(
        dispatchAddressCode,
        this.provinceNameAndIdMap
      )
      // console.log('provinceId :>> ', provinceId)
      console.log('dispatchAddressCode :>> ', dispatchAddressCode)
      console.log('partitionAndCost :>> ', partitionAndCost)
      //  分区为FBA仓库代码
      if (partitionAndCost && dispatchAddressCode in partitionAndCost) {
        expectFreight = partitionAndCost[dispatchAddressCode]

        if (provinceId) {
          console.log('provinceId :>> ', provinceId)
          cf.provinceId = provinceId.toString()
        }
        this.feightMoney = expectFreight
        this.channelform.expectFreight = expectFreight
        this.isDisabledProvinceId = true
        return
      }
      console.log('countryName :>> ', countryName)

      if (countryName.indexOf('美国') > -1) {
        //  根据FBACode取得邮编信息
        if (cf.purposeWarehouseType === 100) {
          if (dispatchAddressCode in this.publicData.fbaCodeZipCodeMap) {
            const fbaCodeZipCode =
              this.publicData.fbaCodeZipCodeMap[dispatchAddressCode]

            console.log('fbaCodeZipCode :>> ', fbaCodeZipCode)
            if (fbaCodeZipCode && fbaCodeZipCode.length > 1) {
              const zipCodeStartStr = fbaCodeZipCode.substr(0, 1)
              if (
                zipCodeStartStr === '0' ||
                zipCodeStartStr === '1' ||
                zipCodeStartStr === '2' ||
                zipCodeStartStr === '3'
              ) {
                dispatchAddressCode = '邮编0、1、2、3开头'
              } else if (
                zipCodeStartStr === '4' ||
                zipCodeStartStr === '5' ||
                zipCodeStartStr === '6' ||
                zipCodeStartStr === '7'
              ) {
                dispatchAddressCode = '邮编4、5、6、7开头'
              } else if (zipCodeStartStr === '8' || zipCodeStartStr === '9') {
                dispatchAddressCode = '邮编8、9开头'
              }
              expectFreight = partitionAndCost[dispatchAddressCode]
            }
          }
        } else {
          expectFreight = partitionAndCost[dispatchAddressCode]
        }
      } else if (
        countryName.indexOf('加拿大') > -1 &&
        dispatchAddressCode.length > 3
      ) {
        dispatchAddressCode = dispatchAddressCode.substr(0, 3)

        if (cf.inStockChannel === 253 && cf.purposeWarehouseType === 100) {
          if (dispatchAddressCode === 'YVR') {
            dispatchAddressCode = 'YVR'
          } else {
            dispatchAddressCode = '加拿大FBA'
          }
        } else {
          if (dispatchAddressCode === 'YVR') {
            dispatchAddressCode = '加拿大YVR'
          } else if (dispatchAddressCode === 'YYZ') {
            dispatchAddressCode = '加拿大YYZ'
          } else if (dispatchAddressCode === 'YYC') {
            dispatchAddressCode = '加拿大YYC'
          }
        }

        expectFreight = partitionAndCost[dispatchAddressCode]
      } else if (countryName.indexOf('澳大利亚') > -1) {
        //  是否FBA仓
        if (cf.purposeWarehouseType === 100) {
          dispatchAddressCode = 'FBA仓'
        } else {
          dispatchAddressCode = '商业地址&海外仓'
        }
        expectFreight = partitionAndCost[dispatchAddressCode]
      }

      // provinceId = this.countryStateMap[dispatchAddressCode]
      provinceId = getFindKey(dispatchAddressCode, this.provinceNameAndIdMap)

      if (provinceId) {
        console.log('122 :>> ', 122)
        cf.provinceId = provinceId.toString()
        this.isDisabledProvinceId = true
      }

      if (
        expectFreight === undefined ||
        expectFreight === null ||
        expectFreight === ''
      ) {
        expectFreight = this.customerChannelForm.feightMoney //  取国家运费
        // cf.provinceId = ''
        this.isDisabledProvinceId = false

        //  判断下单模式 quickOrder/快捷下单
        if (this.orderType === 'quickOrder') {
          // this.$message.error(
          //   '该派送地址无相应运费,请选择分区，或者请刷新重新上传入库装箱单计划'
          // )
          this.isDisabledProvinceId = true
          // cf.dispatchAddressCode = ''
        } else if (cf.provinceId) {
          this.changeProvinceId(cf.provinceId)
        } else {
          // this.$message.error('未找到运单运费，请选择国内分区')
          //  $('#dispatchAddressCode').select2('val', '')
          this.isDisabledProvinceId = true
          cf.dispatchZipCode = ''
          this.feightMoney = expectFreight
          this.channelform.expectFreight = expectFreight
        }
        //

        return
      }
      //  预计运费
      this.feightMoney = expectFreight
      this.channelform.expectFreight = expectFreight
    },

    async uploadFn(params, name) {
      console.log('params', params)
      const isLt50M = params.file.size / 1024 / 1024 < 50

      if (!isLt50M) {
        this.$message.error('上传文件大小不能超过 50MB!')
        return false
      }
      // if (!this.beforeUpload(params.file)) return
      const formData = new FormData()
      // 通过 FormData 对象上传文件
      formData.append(params.file.name, params.file)

      const data = await uploadWaybillFile(formData)
      console.log('data :>> ', data)
      if (data.code === 200) {
        // const obj = clone(this.channelform[name])
        const obj = {}
        obj[data.fileName] = data.fileUrl

        this.$delete(this.channelform, name)
        this.$set(this.channelform, name, obj)
        console.log('this.channelform: ', this.channelform)
      } else {
        this.$message.error('上传失败!')
      }
    },
    uploadExtraAttributes(params) {
      this.uploadFn(params, 'extraAttributes')
    },
    async uploadDeliveryFiles(params) {
      this.uploadFn(params, 'deliveryFilesMap')
    },
    removeFile(name, key) {
      const obj = clone(this.channelform[name])
      delete obj[key]
      this.$delete(this.channelform, name)
      this.$set(this.channelform, name, obj)
    },
    changeEtInStockDay(val) {
      this.changeEtInStock()
    },

    changeEtInStock() {
      const cf = this.channelform
      console.log('cf.etInStockDay :>> ', this.etInStockDay)
      if (this.etInStockDay && this.etInStockTime) {
        this.$delete(cf, 'etInStock')
        this.$set(cf, 'etInStock', this.etInStockDay + ' ' + this.etInStockTime)
      } else {
        this.$delete(cf, 'etInStock')
        this.$set(cf, 'etInStock', '')
      }
    },
    changeZipCode() {
      if (this.timer2) {
        clearTimeout(this.timer2)
      }
      this.timer2 = setTimeout(() => {
        this.checkChannelSearchCriteria()
      }, 1000)
    }
  }
}
</script>

<style lang="scss" scoped>
.icon-question {
  font-size: 18px;
  //  vertical-align: text-top;
  margin-left: 10px;
}

.icon-absolute {
  position: absolute;
  right: -24px;
  font-size: 18px;
  top: 50%;
  margin-top: -9px;
}
ul {
  list-style: none;

  li {
    margin-bottom: 12px;
  }
}
</style>
<style lang="scss">
.text-tips {
  color: red;
  .el-form-item__label {
    color: red;
  }
}

.left-container {
  .text-row {
    .el-form-item__content {
      font-size: 12px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
  .el-upload {
    text-align: left;
  }
}
.text-right {
  .el-form-item__content {
    text-align: left;
  }
}

.card-main {
  padding: 20px 20px 0;
  position: relative;
  &:not(:last-child) {
    margin-bottom: 20px;
  }
  .el-form .el-form-item--mini.el-form-item,
  .el-form .el-form-item--small.el-form-item {
    margin-bottom: 0;
  }
}
.el-card.is-always-shadow.selectCart {
  box-shadow: 0 2px 12px 0 rgba(67, 201, 162, 1);
}
@media screen and (min-width: 1200px) {
  .text-right {
    .el-form-item__label {
      text-align: right;
    }
  }
}
</style>
